from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import List, Optional
import uuid
from datetime import datetime
import random

router = APIRouter()

class MonitorRecord(BaseModel):
    time: str
    show: str
    session: str
    status: str
    stock: int
    orderId: Optional[str] = None

class OrderDetail(BaseModel):
    orderId: str
    showName: str
    session: str
    price: str
    count: int
    total: float
    status: str
    screenshot: str

# 模拟监控数据
monitor_data = []
order_data = {}

@router.get("/check")
async def check_inventory():
    """检查库存状态"""
    # 模拟库存检查
    import time
    
    # 生成随机库存数据
    shows = ["周杰伦演唱会", "林俊杰演唱会", "五月天演唱会"]
    sessions = ["2024-12-15 19:30", "2024-12-16 19:30", "2024-12-20 19:30"]
    
    record = {
        "time": datetime.now().strftime("%H:%M:%S"),
        "show": random.choice(shows),
        "session": random.choice(sessions),
        "status": "有票" if random.random() > 0.7 else "无票",
        "stock": random.randint(0, 50),
        "orderId": None
    }
    
    monitor_data.append(record)
    
    # 限制数据条数
    if len(monitor_data) > 50:
        monitor_data.pop(0)
    
    # 模拟统计数据
    stats = {
        "total": len(monitor_data),
        "success": len([r for r in monitor_data if r["status"] == "有票"]),
        "fail": len([r for r in monitor_data if r["status"] == "无票"])
    }
    
    return {
        "records": monitor_data[-10:],  # 返回最近10条
        "stats": stats,
        "hasStock": record["status"] == "有票"
    }

@router.get("/order/{order_id}")
async def get_order_detail(order_id: str):
    """获取订单详情"""
    # 模拟订单数据
    order = {
        "orderId": order_id,
        "showName": "周杰伦2024巡回演唱会",
        "session": "2024-12-15 19:30",
        "price": "580元",
        "count": 2,
        "total": 1160.0,
        "status": "成功",
        "screenshot": f"https://via.placeholder.com/800x600/28a745/FFFFFF?text=订单截图-{order_id}"
    }
    
    return order

@router.get("/history")
async def get_monitor_history(limit: int = 20):
    """获取监控历史"""
    return {
        "records": monitor_data[-limit:],
        "total": len(monitor_data)
    }

@router.post("/screenshot")
async def save_screenshot(order_id: str):
    """保存订单截图"""
    # 模拟截图保存
    screenshot_url = f"https://via.placeholder.com/800x600/28a745/FFFFFF?text=订单截图-{order_id}"
    
    return {
        "success": True,
        "url": screenshot_url,
        "message": "截图保存成功"
    }

@router.get("/status")
async def get_monitor_status():
    """获取监控状态"""
    return {
        "isRunning": True,
        "startTime": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "monitoredShows": 3,
        "totalChecks": len(monitor_data)
    }

@router.post("/alert")
async def set_alert_config(show_id: str, price_range: str, target_count: int):
    """设置库存提醒"""
    return {
        "success": True,
        "message": "提醒设置成功",
        "config": {
            "showId": show_id,
            "priceRange": price_range,
            "targetCount": target_count
        }
    }